//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { Button, Card, Input, message, Space } from 'antd';
import { useDrawStores } from '../store';
import s from "./EditDraw.module.less";
import { report_error } from '@/api/client_cfg';
import { get_session } from '@/api/user';
import { request } from '@/utils/request';
import { end_update_draw, keep_update_draw, start_update_draw, update_draw } from '@/api/project_draw';
import { update_title } from "@/api/project_entry";
import { createTLStore, Tldraw, type TLUiOverrides } from 'tldraw';

const WriteDraw = () => {
    const store = useDrawStores();
    const [title, setTitle] = useState(store.entry?.entry_title ?? "");
    const [contentStore] = useState(createTLStore());

    const myOverrides: TLUiOverrides = {
        actions(_, actions) {
            const nameList = ["copy-as-svg", "copy-as-png", "copy-as-json", "export-as-svg",
                "export-as-png", "export-as-json", "edit-link", "export-all-as-svg", "export-all-as-png", "export-all-as-json", "insert-media"];
            for (const name of nameList) {
                delete actions[name];
            }
            return actions;
        },
        tools(_, tools) {
            delete tools["asset"];
            delete tools["embed"];
            return tools;
        }
    }


    const updateDraw = async () => {
        const sessionId = await get_session();
        const data = contentStore.getStoreSnapshot();
        await request(update_draw({
            session_id: sessionId,
            project_id: store.projectId,
            draw_id: store.drawId,
            content: JSON.stringify(data),
        }));

        if (title != store.entry?.entry_title) {
            await request(update_title({
                session_id: sessionId,
                project_id: store.projectId,
                entry_id: store.drawId,
                title: title,
            }));
        }

        await store.loadDraw();
        store.inEdit = false;
    };


    const keepUpdateDraw = async () => {
        const sessionId = await get_session();
        await request(
            keep_update_draw({
                session_id: sessionId,
                draw_id: store.drawId,
            }),
        )
    };

    const startUpdateDraw = async () => {
        const sessionId = await get_session();
        await request(
            start_update_draw({
                session_id: sessionId,
                project_id: store.projectId,
                draw_id: store.drawId,
            }),
        )
    };


    const endUpdateDraw = async () => {
        const sessionId = await get_session();
        await request(end_update_draw({
            session_id: sessionId,
            draw_id: store.drawId,
        }));
    };

    useEffect(() => {
        const timer = setInterval(() => {
            keepUpdateDraw().catch((e) => {
                console.log(e);
                report_error({
                    err_data: `${e}`,
                });
                message.error('无法维持编辑状态');
            });
        }, 10 * 1000);
        startUpdateDraw().catch((e) => {
            console.log(e);
            report_error({
                err_data: `${e}`,
            });
            message.error('无法获得编辑权限');
        });
        return () => {
            clearInterval(timer);
            endUpdateDraw();
        };
    }, []);

    useEffect(() => {
        return () => {
            store.inEdit = false;
        };
    }, []);

    useEffect(() => {
        if (store.draw != undefined && store.draw.content != "") {
            const data = JSON.parse(store.draw.content);
            contentStore.loadStoreSnapshot(data);
        }
    }, []);

    return (
        <Card bordered={false}
            title={
                <Input value={title} onChange={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    setTitle(e.target.value.trim());
                }} />
            }
            bodyStyle={{ width: "calc(100vw - 10px)" }}
            extra={
                <Space size="large" style={{ marginLeft: "100px", marginRight: "30px" }}>
                    <Button
                        type="default"
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            store.inEdit = false;
                        }}>取消</Button>
                    <Button
                        type="primary"
                        onClick={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                            updateDraw();
                        }}
                        disabled={title == ""}
                    >
                        保存
                    </Button>
                </Space>}>
            <div className={s.draw_wrap}>
                <Tldraw store={contentStore} overrides={myOverrides} components={{
                    MainMenu: null,
                    SharePanel: null,
                    CursorChatBubble: null,
                }} onMount={(editor) => {
                    editor.user.updateUserPreferences({
                        locale: "zh-cn",
                    });
                    setTimeout(() => {
                        editor.user.updateUserPreferences({
                            locale: "zh-cn",
                        });
                    }, 200);
                }} />
            </div>
        </Card>
    );
};

export default observer(WriteDraw);
